<!--
 * @Descripttion: 应用管理-新建
 * @Author: 何伟伦 weilun@ssc-hn.com
 * @Date: 2024-03-21
 * @LastEditors: 何伟伦 weilun@ssc-hn.com
 * @LastEditTime: 2024-03-29
-->
<script lang="ts" setup>
  import { ArrowLeftOutlined, LoadingOutlined, PlusOutlined } from '@ant-design/icons-vue'
  import { message, Upload } from 'ant-design-vue'
  import { reactive, ref } from 'vue'
  import { useRouter } from 'vue-router'

  import { requestSaveAppInfo } from '/@/api/system/app/config'
  import { HttpCodeEnum } from '/@/enums/httpEnum'
  import { getToken } from '/@/storage'
  const token = getToken() || ''

  const uploadApi = `${import.meta.env.VITE_BASE_API_PATH}/contentFile/upload/V1`
  const router = useRouter()

  const formRef = ref()
  const formState = ref({
    clientName: '',
    appRemark: '',
    appImage: '',
    appType: null,
  })

  const fileList = ref([])

  const variable = reactive({
    confirmLoading: false,
    uploadLoading: false,
  })

  const beforeUpload = (file) => {
    const fileSizeKB = file.size / 1024
    const isPng = ['.png'].includes(file.name.substr(file.name.lastIndexOf('.')).toLowerCase())
    if (!isPng) {
      message.error('仅支持png格式文件')
      return false || Upload.LIST_IGNORE
    } else if (fileSizeKB > 300) {
      message.error('文件大小超过300KB，请选择一个较小的文件。')
      return false || Upload.LIST_IGNORE
    } else {
      const img = new Image()
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => {
        img.src = reader.result as string
      }
      img.onload = () => {
        if (img.width !== 28 || img.height !== 28) {
          message.error('图片尺寸必须为28x28像素。')
          return false || Upload.LIST_IGNORE
        } else {
          return true
        }
      }
    }
  }

  const handleChange = (info) => {
    if (info.file.status === 'uploading') {
      variable.uploadLoading = true
      return
    }
    if (info.file.status === 'done') {
      message.success('上传成功')
      formState.value.appImage = info.file.response.responseData
      variable.uploadLoading = false
    }
    if (info.file.status === 'error') {
      variable.uploadLoading = false
      message.error(info.file.response.responseMessage || '上传错误')
    }
  }

  const confirm = () => {
    formRef.value
      .validate()
      .then(async () => {
        variable.confirmLoading = true
        const { responseCode } = await requestSaveAppInfo({ ...formState.value }).finally(() => {
          variable.confirmLoading = false
        })

        if (responseCode === HttpCodeEnum.SUCCESS) {
          message.success(`新建应用成功`)
          router.back()
        }
      })
      .catch((res) => {
        console.log('catch: ', res)
      })
  }
</script>

<template>
  <div class="apply-list-add">
    <div class="add-header">
      <arrow-left-outlined :style="{ 'font-weight': 'bold', 'margin-right': '18px' }" @click="router.back()" />
      <span>新建应用</span>
    </div>
    <a-divider />
    <div class="add-form-box">
      <div class="add-title">
        <span class="title">应用信息</span>
      </div>
      <div class="add-content">
        <a-form :model="formState" layout="horizontal" ref="formRef" name="add_form" labelAlign="left">
          <a-form-item label="应用名称" name="clientName" :rules="[{ required: true, message: '请输入应用名称' }]">
            <a-input v-model:value="formState.clientName" allow-clear />
          </a-form-item>
          <a-form-item label="应用简介" name="appRemark" :rules="[{ required: true, message: '请输入应用简介' }]">
            <a-textarea :rows="4" v-model:value="formState.appRemark" allow-clear :maxlength="300" />
          </a-form-item>
          <a-form-item class="w-[50%]" name="appImage" label="应用图片" :rules="[{ required: true, message: '请上传应用图片' }]" extra="请上传移动应用水印图片28*28像素，仅支持PNG格式，大小不超过300KB">
            <a-upload v-model:file-list="fileList" name="file" list-type="picture-card" :maxCount="1" class="avatar-uploader" :action="uploadApi" :headers="{ authorization: token }" :before-upload="beforeUpload" @change="handleChange">
              <div>
                <loading-outlined v-if="variable.uploadLoading" :style="{ color: '#13c2c2' }" />
                <plus-outlined v-else :style="{ color: '#13c2c2' }" />
                <div class="ant-upload-text">上传文件</div>
              </div>
            </a-upload>
          </a-form-item>
          <a-form-item label="应用类别" name="appType" :rules="[{ required: true, message: '请选择类别' }]">
            <a-select v-model:value="formState.appType" placeholder="请选择类别">
              <a-select-option :value="1">数据集</a-select-option>
              <a-select-option :value="2">模型算法</a-select-option>
              <a-select-option :value="3">算力</a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </div>
      <div class="btn-wrap">
        <a-space>
          <a-button type="primary" html-type="submit" @click="confirm">确认</a-button>
          <a-button type="default" html-type="submit" @click="router.back()">取消</a-button>
        </a-space>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
  .apply-list-add {
    background: #fff;
    padding-bottom: 32px;

    .add-header {
      font-size: 18px;
      font-weight: 500;
      color: #000;
      padding: 22px 0 0 26px;
    }

    .add-form-box {
      width: 80%;
      margin: 24px auto;

      .add-title {
        margin-bottom: 24px;
        clear: both;

        &::before {
          content: '';
          width: 3px;
          height: 13px;
          display: inline-block;
          background: #13c2c2;
          margin-right: 3px;
        }

        .title {
          font-size: 16px;
          font-weight: 500;
          color: #00474f;

          &::before {
            content: '';
            width: 2px;
            height: 10px;
            display: inline-block;
            background: #13c2c2;
            margin-right: 8px;
          }
        }
      }
    }
  }
</style>
